package com.lyx.raindrop.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lyx.framework.adapter.CommonAdapter;
import com.lyx.framework.adapter.CommonViewHolder;
import com.lyx.framework.base.BaseBackActivity;
import com.lyx.framework.bmob.BmobManager;
import com.lyx.framework.cloud.CloudManager;
import com.lyx.framework.entity.Constants;
import com.lyx.framework.event.EventManager;
import com.lyx.framework.event.MessageEvent;
import com.lyx.framework.gson.TextBean;
import com.lyx.framework.gson.VoiceBean;
import com.lyx.framework.helper.FileHelper;
import com.lyx.framework.utils.CommonUtils;
import com.lyx.framework.utils.LogUtils;
import com.lyx.framework.utils.statusbar.StatusBarUtil;
import com.lyx.raindrop.R;
import com.lyx.raindrop.adapter.ChatAdapter;
import com.lyx.raindrop.constants.ChatConstants;
import com.lyx.raindrop.model.ChatModel;
import com.lyx.raindrop.model.ChatObjectModel;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.TextMessage;

public class ChatActivity extends BaseBackActivity implements View.OnClickListener {

    /**
     *
     * 发送文本逻辑
     * 1.跳转到ChatActivity
     * 2.实现我们的聊天列表 适配器
     * 3.加载我们的历史记录
     * 4.实时更新我们的聊天信息
     * 5.发送消息
     */

    /**
     * 发送图片逻辑
     * 1.读取(相机和相册)
     * 2.发送图片消息
     * 3.完成我们适配器的UI
     * 4.完成Service的图片接收逻辑
     * 5.通知UI刷新
     */

    /**
     * 发送地址的逻辑
     * 1.获取地址
     * 2.发送位置消息
     * 不能忘记：
     * 1.历史消息
     * 2.适配器
     * 3.发送消息
     */

    private static final int LOCATION_REQUEST_CODE = 1888;
    private static final int CHAT_INFO_REQUEST_CODE = 1889;

    public static void startActivity(Context mContext, String userId, String userName, String userPhoto) {
        if (!CloudManager.getInstance().isConnect()) {
            Toast.makeText(mContext, mContext.getString(R.string.text_server_status), Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(mContext, ChatActivity.class);
        intent.putExtra(Constants.INTENT_USER_ID, userId);
        intent.putExtra(Constants.INTENT_USER_NAME, userName);
        intent.putExtra(Constants.INTENT_USER_PHOTO, userPhoto);
        mContext.startActivity(intent);
    }

    //聊天列表
    private RecyclerView mChatView;
    //输入框
    private EditText et_input_msg;
    //发送按钮
    private Button btn_send_msg;
    //语音输入
    private LinearLayout ll_voice;
    //相机
    private LinearLayout ll_camera;
    //图片
    private LinearLayout ll_pic;
    //位置
    private LinearLayout ll_location;

    //对方用户信息
    private ChatObjectModel mChatObjectModel;

    //自己的信息
    private String meUserPhoto;

    //列表
    private ChatAdapter adapter;
    private List<ChatModel> mList = new ArrayList<>();

    //图片文件
    private File uploadFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        meUserPhoto = BmobManager.getInstance().getUser().getPhoto();
        loadChatObjectInfo();
        initView();
        queryMessage();
    }

    private void initView() {
        mChatView = findViewById(R.id.mChatView);
        et_input_msg = findViewById(R.id.et_input_msg);
        btn_send_msg = findViewById(R.id.btn_send_msg);
        ll_voice = findViewById(R.id.ll_voice);
        ll_camera = findViewById(R.id.ll_camera);
        ll_pic = findViewById(R.id.ll_pic);
        ll_location = findViewById(R.id.ll_location);
        btn_send_msg.setOnClickListener(this);
        ll_voice.setOnClickListener(this);
        ll_camera.setOnClickListener(this);
        ll_pic.setOnClickListener(this);
        ll_location.setOnClickListener(this);
        et_input_msg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (mList.isEmpty()) {
                        return;
                    }
                    mChatView.scrollToPosition(mList.size() - 1);
                }
            }
        });

        mChatView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ChatAdapter(this, mList, mChatObjectModel);
        mChatView.setAdapter(adapter);
    }

    //查询聊天记录
    private void queryMessage() {
        CloudManager.getInstance().getHistoryMessages(mChatObjectModel.getId(), new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                if (CommonUtils.isEmpty(messages)) {
                    try {
                        parsingListMessage(messages);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    queryRemoteMessage();
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                LogUtils.getInstance().e("errorCode:" + errorCode);
            }
        });
    }

    //解析历史记录
    private void parsingListMessage(List<Message> messages) {
        //倒序
        Collections.reverse(messages);
        //遍历
        for (int i = 0; i < messages.size(); i++) {
            Message m = messages.get(i);
            String objectName = m.getObjectName();
            if (objectName.equals(CloudManager.MSG_TEXT_NAME)) {
                TextMessage textMessage = (TextMessage) m.getContent();
                String msg = textMessage.getContent();
                try {
                    TextBean textBean = new Gson().fromJson(msg, TextBean.class);
                    if (textBean.getType().equals(CloudManager.TYPE_TEXT)) {
                        //添加到UI 判断是你 还是 我
                        if (m.getSenderUserId().equals(mChatObjectModel.getId())) {
                            addText(0, textBean.getMsg());
                        } else {
                            addText(1, textBean.getMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (objectName.equals(CloudManager.MSG_IMAGE_NAME)) {
                ImageMessage imageMessage = (ImageMessage) m.getContent();
                String url = imageMessage.getRemoteUri().toString();
                if (!TextUtils.isEmpty(url)) {
                    if (m.getSenderUserId().equals(mChatObjectModel.getId())) {
                        addImage(0, url);
                    } else {
                        addImage(1, url);
                    }
                }
            } else if (objectName.equals(CloudManager.MSG_LOCATION_NAME)) {
                LocationMessage locationMessage = (LocationMessage) m.getContent();
                if (m.getSenderUserId().equals(mChatObjectModel.getId())) {
                    addLocation(0, locationMessage.getLat(),
                            locationMessage.getLng(), locationMessage.getPoi());
                } else {
                    addLocation(1, locationMessage.getLat(),
                            locationMessage.getLng(), locationMessage.getPoi());
                }
            }
        }
    }

    //查询服务器历史记录
    private void queryRemoteMessage() {
        CloudManager.getInstance().getRemoteHistoryMessages(mChatObjectModel.getId(), new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                if (CommonUtils.isEmpty(messages)) {
                    try {
                        parsingListMessage(messages);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                LogUtils.getInstance().e("errorCode:" + errorCode);
            }
        });
    }

    //加载聊天对象的信息
    private void  loadChatObjectInfo() {
        Intent intent = getIntent();
        mChatObjectModel = new ChatObjectModel();
        mChatObjectModel.setId(intent.getStringExtra(Constants.INTENT_USER_ID));
        mChatObjectModel.setName(intent.getStringExtra(Constants.INTENT_USER_NAME));
        mChatObjectModel.setPhoto(intent.getStringExtra(Constants.INTENT_USER_PHOTO));
        //设置标题
        if (!TextUtils.isEmpty(mChatObjectModel.getName())) {
            getSupportActionBar().setTitle(mChatObjectModel.getName());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_msg:
                String inputText = et_input_msg.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    return;
                }
                CloudManager.getInstance().sendTextMessage(inputText,
                        CloudManager.TYPE_TEXT, mChatObjectModel.getId());
                addText(1, inputText);
                //清空
                et_input_msg.setText("");
                break;
//            case R.id.ll_voice:
//                VoiceManager.getInstance(this).startSpeak(new RecognizerDialogListener() {
//                    @Override
//                    public void onResult(RecognizerResult recognizerResult, boolean b) {
//                        String result = recognizerResult.getResultString();
//                        if (!TextUtils.isEmpty(result)) {
//                            LogUtils.i("result:" + result);
//                            VoiceBean voiceBean = new Gson().fromJson(result, VoiceBean.class);
//                            if (voiceBean.isLs()) {
//                                StringBuffer sb = new StringBuffer();
//                                for (int i = 0; i < voiceBean.getWs().size(); i++) {
//                                    VoiceBean.WsBean wsBean = voiceBean.getWs().get(i);
//                                    String sResult = wsBean.getCw().get(0).getW();
//                                    sb.append(sResult);
//                                }
//                                LogUtils.i("result:" + sb.toString());
//                                et_input_msg.setText(sb.toString());
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(SpeechError speechError) {
//                        LogUtils.e("speechError:" + speechError.toString());
//                    }
//                });
//                break;
            case R.id.ll_camera:
                FileHelper.getInstance().toCamera(this);
                break;
            case R.id.ll_pic:
                FileHelper.getInstance().toAlbum(this);
                break;
            case R.id.ll_location:
//                LocationActivity.startActivity(this, true, 0, 0, "", LOCATION_REQUEST_CODE);
                break;
        }
    }

    //添加数据的基类
    private void baseAddItem(ChatModel model) {
        mList.add(model);
        adapter.notifyDataSetChanged();
        //滑动到底部
        mChatView.scrollToPosition(mList.size() - 1);
    }

    //添加文字
    private void addText(int index, String text) {
        ChatModel model = new ChatModel();
        if (index == 0) {
            model.setType(ChatConstants.TYPE_LEFT_TEXT);
        } else {
            model.setType(ChatConstants.TYPE_RIGHT_TEXT);
        }
        model.setText(text);
        baseAddItem(model);
    }

    //添加图片
    private void addImage(int index, String url) {
        ChatModel model = new ChatModel();
        if (index == 0) {
            model.setType(ChatConstants.TYPE_LEFT_IMAGE);
        } else {
            model.setType(ChatConstants.TYPE_RIGHT_IMAGE);
        }
        model.setImgUrl(url);
        baseAddItem(model);
    }

    //添加图片
    private void addImage(int index, File file) {
        ChatModel model = new ChatModel();
        if (index == 0) {
            model.setType(ChatConstants.TYPE_LEFT_IMAGE);
        } else {
            model.setType(ChatConstants.TYPE_RIGHT_IMAGE);
        }
        model.setLocalFile(file);
        baseAddItem(model);
    }

    //添加地址
    private void addLocation(int index, double la, double lo, String address) {
        ChatModel model = new ChatModel();
        if (index == 0) {
            model.setType(ChatConstants.TYPE_LEFT_LOCATION);
        } else {
            model.setType(ChatConstants.TYPE_RIGHT_LOCATION);
        }
        model.setLa(la);
        model.setLo(lo);
        model.setAddress(address);
//        model.setMapUrl(MapManager.getInstance().getMapUrl(la, lo));
        baseAddItem(model);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (!event.getUserId().equals(mChatObjectModel.getId())) {
            return;
        }
        switch (event.getType()) {
            case EventManager.FLAG_SEND_TEXT:
                addText(0, event.getText());
                break;
            case EventManager.FLAG_SEND_IMAGE:
                addImage(0, event.getImgUrl());
                break;
            case EventManager.FLAG_SEND_LOCATION:
                addLocation(0, event.getLa(), event.getLo(), event.getAddress());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FileHelper.CAMERA_REQUEST_CODE) {
                uploadFile = FileHelper.getInstance().getTempFile();
            } else if (requestCode == FileHelper.ALBUM_REQUEST_CODE) {
                Uri uri = data.getData();
                if (uri != null) {
                    //String path = uri.getPath();
                    //获取真实的地址
                    String path = FileHelper.getInstance().getRealPathFromURI(this, uri);
                    //LogUtils.e("path:" + path);
                    if (!TextUtils.isEmpty(path)) {
                        uploadFile = new File(path);
                    }
                }
            } else if (requestCode == LOCATION_REQUEST_CODE) {
                double la = data.getDoubleExtra("la", 0);
                double lo = data.getDoubleExtra("lo", 0);
                String address = data.getStringExtra("address");
                if (TextUtils.isEmpty(address)) {
//                    MapManager.getInstance().poi2address(la, lo, new MapManager.OnPoi2AddressGeocodeListener() {
//                        @Override
//                        public void poi2address(String address) {
//                            //发送位置消息
//                            CloudManager.getInstance().sendLocationMessage(yourUserId, la, lo, address);
//                            addLocation(1, la, lo, address);
//                        }
//                    });
                } else {
                    //发送位置消息
//                    CloudManager.getInstance().sendLocationMessage(yourUserId, la, lo, address);
                    addLocation(1, la, lo, address);
                }

            } else if (requestCode == CHAT_INFO_REQUEST_CODE) {
                finish();
            }
            if (uploadFile != null) {
                //发送图片消息
                CloudManager.getInstance().sendImageMessage(mChatObjectModel.getId(), uploadFile);
                //更新列表
                addImage(1, uploadFile);
                uploadFile = null;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.chat_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_chat_menu:
                ChatInfoActivity.startChatInfo(this, mChatObjectModel.getId(), CHAT_INFO_REQUEST_CODE);
                break;
            case R.id.menu_chat_audio:
                if (!checkWindowPermissions()) {
                    requestWindowPermissions();
                } else {
//                    CloudManager.getInstance().startAudioCall(this, yourUserId);
                }
                break;
            case R.id.menu_chat_video:
//                if (!checkWindowPermissions()) {
//                    requestWindowPermissions();
//                } else {
////                    CloudManager.getInstance().startVideoCall(this, yourUserId);
//                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
